<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模板名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="启用" value="0"/>
          <el-option label="停用" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supply:template:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supply:flowTemplate:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supply:template:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格区域 -->
    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange" row-key="id">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" type="index" width="50"/>
      <el-table-column label="关联的订单索引" align="center" prop="orderId"/>
      <el-table-column label="模板名称" align="center" prop="templateName" :show-overflow-tooltip="true"/>
      <el-table-column label="模板描述" align="center" prop="templateDesc" :show-overflow-tooltip="true"/>
      <el-table-column label="流程类型" align="center" prop="flowType" :formatter="flowTypeFormat"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="签名记录" align="center" min-width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.signatureImage" class="signature-list">
            <el-image
              v-for="(img, index) in getSignatureImages(scope.row.signatureImage)"
              :key="index"
              :src="img"
              :preview-src-list="getSignatureImages(scope.row.signatureImage)"
              class="signature-thumb"
              fit="contain">
              <div slot="error" class="image-error">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </div>
          <span v-else>暂无签名</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"

            v-hasPermi="['supply:template:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
          >预览
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supply:template:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改审批流程模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body>
      <el-tabs v-model="activeName" tab-position="top">
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="模板名称" prop="templateName">
                  <el-input v-model="form.templateName" placeholder="请输入模板名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="流程类型" prop="flowType">
                  <el-select v-model="form.flowType" placeholder="请选择流程类型">
                    <el-option label="采购审批" value="purchase"/>
                    <el-option label="销售审批" value="sales"/>
                    <el-option label="人事审批" value="hr"/>
                    <el-option label="财务审批" value="finance"/>
                    <el-option label="其他审批" value="other"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="模板状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio
                      v-for="dict in dict.type.sys_normal_disable"
                      :key="dict.value"
                      :label="dict.value"
                    >{{ dict.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="模板描述" prop="templateDesc">
                  <el-input v-model="form.templateDesc" type="textarea" placeholder="请输入模板描述"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="关联订单" prop="orderId">
                  <el-input v-model="form.orderId" placeholder="请输入订单ID" disabled/>
                  <el-button size="small" type="primary" @click="openOrderSelectForTemplate">选择订单</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="流程设计" name="design">
          <div class="flow-design-container">
            <!-- 节点工具箱 -->
            <div class="node-toolbox">
              <div class="toolbox-title">审批节点工具</div>
              <div class="node-item-list">
                <div
                  class="node-item"
                  draggable="true"
                  @dragstart="handleDragStart($event, 'approval')"
                >
                  <i class="el-icon-s-check"></i>
                  <span>审批节点</span>
                </div>
              </div>
            </div>

            <!-- 流程设计区域 -->
            <div
              class="flow-canvas"
              @dragover.prevent
              @drop="handleDrop"
            >
              <div v-if="nodeList.length === 0" class="flow-empty">
                <i class="el-icon-plus"></i>
                <p>将左侧节点拖拽到此处构建流程</p>
                <el-button type="primary" size="small" @click="addNodeManually">添加节点</el-button>
              </div>

              <template v-else>
                <!-- 开始节点 -->
                <div class="flow-start">
                  <div class="start-node">
                    <i class="el-icon-s-platform"></i>
                    <span>开始</span>
                  </div>
                  <div class="flow-connector"></div>
                </div>

                <!-- 流程节点列表 -->
                <draggable
                  v-model="nodeList"
                  class="node-list"
                  ghost-class="ghost-node"
                  handle=".node-drag-handle"
                  animation="300"
                >
                  <div
                    v-for="(node, index) in nodeList"
                    :key="index"
                    class="flow-node-wrapper"
                  >
                    <div class="flow-node approval-node">
                      <div class="node-header">
                        <div class="node-title">
                          <i class="el-icon-s-check"></i>
                          <span>{{ node.nodeName }}</span>
                        </div>
                        <div class="node-actions">
                          <i class="el-icon-rank node-drag-handle" title="拖动排序"></i>
                          <i class="el-icon-edit" @click="editNode(node, index)" title="编辑节点"></i>
                          <i class="el-icon-delete" @click="deleteNode(index)" title="删除节点"></i>
                        </div>
                      </div>
                      <div class="node-content">
                        <div class="node-info">
                          <p class="info-item">
                            <span class="info-label">审批角色:</span>
                            <span class="info-value">{{ formatRoles(node.approvalRoles) }}</span>
                          </p>
                          <p class="info-item">
                            <span class="info-label">审批人员:</span>
                            <span class="info-value">{{ formatApprovalUsers(node.approvalUsers) }}</span>
                          </p>
                          <p class="info-item" v-if="node.needSignature">
                            <span class="info-label">电子签名:</span>
                            <span class="info-value"><i class="el-icon-checked"></i> 已启用</span>
                            <el-button size="mini" type="text" @click="previewQrCode(node)" class="qrcode-btn">
                              <i class="el-icon-picture-outline"></i> 查看二维码
                            </el-button>
                          </p>
                        </div>
                      </div>
                    </div>

                    <!-- 连接线 -->
                    <div v-if="index < nodeList.length - 1" class="flow-connector">
                      <i class="el-icon-arrow-down"></i>
                    </div>
                  </div>
                </draggable>

                <!-- 结束节点 -->
                <div class="flow-end">
                  <div class="flow-connector"></div>
                  <div class="end-node">
                    <i class="el-icon-s-release"></i>
                    <span>结束</span>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 节点编辑对话框 -->
    <el-dialog :title="nodeForm.isNew ? '添加审批节点' : '编辑审批节点'" :visible.sync="nodeDialog" width="650px"
               append-to-body>
      <el-form ref="nodeForm" :model="nodeForm" :rules="nodeRules" label-width="100px">
        <el-form-item label="节点名称" prop="nodeName">
          <el-input v-model="nodeForm.nodeName" placeholder="请输入节点名称"/>
        </el-form-item>

        <el-form-item label="审批角色" prop="approvalRoles">
          <el-input
            v-model="nodeForm.approvalRolesInput"
            placeholder="请输入审批角色，多个角色用逗号分隔"
            @blur="handleRolesInput"
          />
          <div class="expr-tips">多个审批角色请用逗号分隔，例如：部门经理,总监,财务经理</div>
        </el-form-item>

        <el-form-item label="审批人员" prop="approvalUsers">
          <el-input
            v-model="nodeForm.approvalUsersInput"
            placeholder="请输入审批人员姓名，多个人员用逗号分隔"
            @blur="handleUsersInput"
          />
          <div class="expr-tips">多个审批人员请用逗号分隔，例如：1,2,3</div>
        </el-form-item>

        <el-form-item label="电子签名" prop="needSignature">
          <el-switch
            v-model="nodeForm.needSignature"
            active-text="需要电子签名"
            inactive-text="不需要电子签名">
          </el-switch>
          <div class="expr-tips">启用后将生成电子签名二维码，扫描后可进行审批签名</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="nodeDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitNodeForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 订单选择对话框 -->
    <el-dialog title="选择关联订单" :visible.sync="orderSelectDialogVisible" width="900px" append-to-body>
      <div class="order-select-dialog">
        <!-- 订单搜索表单 -->
        <el-form :model="orderQueryParams" :inline="true" size="small" class="order-search-form">
          <el-form-item label="订单号">
            <el-input v-model="orderQueryParams.orderNumber" placeholder="请输入订单号" clearable></el-input>
          </el-form-item>
          <el-form-item label="订单日期">
            <el-date-picker
              v-model="orderQueryParams.orderDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              clearable
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="searchOrders">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetOrderSearch" v-has-permi="['supply:template:query']">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 订单表格 -->
        <el-table
          v-loading="orderLoading"
          :data="orderList"
          @row-click="handleOrderSelect"
          highlight-current-row
          border
          style="width: 100%"
        >
          <el-table-column label="订单ID" prop="orderId" min-width="80"></el-table-column>
          <el-table-column label="订单号" prop="orderNumber" min-width="120"></el-table-column>
          <el-table-column label="订单金额" prop="orderAmount" min-width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.orderAmount }}
            </template>
          </el-table-column>
          <el-table-column label="支付方式" prop="paymentMethod" min-width="100"></el-table-column>
          <el-table-column label="订单日期" prop="orderDate" min-width="120"></el-table-column>
          <el-table-column label="订单状态" prop="orderStatus" min-width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.orderStatus === '0' ? 'success' : 'warning'">
                {{ scope.row.orderStatus === '0' ? '已支付' : '待支付' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-check"
                @click.stop="selectOrder(scope.row)"
              >选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="orderTotal > 0"
          :total="orderTotal"
          :page.sync="orderQueryParams.pageNum"
          :limit.sync="orderQueryParams.pageSize"
          @pagination="getOrderList"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="orderSelectDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 预览流程图对话框 -->
    <el-dialog title="预览审批流程" :visible.sync="previewOpen" width="900px" append-to-body>
      <div class="flow-preview-container">
        <div class="flow-preview">
          <div v-if="!previewData || !previewData.nodes || previewData.nodes.length === 0" class="no-data">
            <i class="el-icon-warning-outline"></i>
            <p>暂无流程数据</p>
          </div>

          <template v-else>
            <div class="flow-start">
              <div class="start-node">
                <i class="el-icon-s-platform"></i>
                <span>开始</span>
              </div>
              <div class="flow-connector"></div>
            </div>

            <div
              v-for="(node, index) in previewData.nodes"
              :key="index"
              class="flow-node-wrapper"
            >
              <div class="flow-node">
                <div class="node-icon">
                  <i class="el-icon-s-check"></i>
                </div>
                <div class="node-content">
                  <div class="node-title">{{ node.nodeName }}</div>
                  <div class="node-info">
                    <p v-if="node.approvalRoles && node.approvalRoles.length">
                      审批角色: {{ formatRoles(node.approvalRoles) }}
                    </p>
                    <p v-if="node.approvalUsers && node.approvalUsers.length">
                      审批人员: {{ formatApprovalUsers(node.approvalUsers) }}
                    </p>
                    <p>审批人数: {{ node.approverCount || 1 }}</p>
                    <p v-if="node.needSignature">
                      电子签名: <i class="el-icon-check success-icon"></i> 已启用
                      <el-button
                        size="mini"
                        type="text"
                        @click="previewQrCode(node)"
                        class="btn-margin">
                        <i class="el-icon-picture-outline"></i> 查看二维码
                      </el-button>
                    </p>
                    <!-- 添加签名图片展示部分 -->
                    <div v-if="node.signatureImage" class="signature-images">
                      <p>签名记录:</p>
                      <div class="image-list">
                        <el-image
                          v-for="(img, imgIndex) in getSignatureImages(node.signatureImage)"
                          :key="imgIndex"
                          :src="img"
                          :preview-src-list="getSignatureImages(node.signatureImage)"
                          class="signature-thumb"
                          fit="contain">
                          <div slot="error" class="image-error">
                            <i class="el-icon-picture-outline"></i>
                          </div>
                        </el-image>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 连接线 -->
              <div v-if="index < previewData.nodes.length - 1" class="flow-connector">
                <i class="el-icon-arrow-down"></i>
              </div>
            </div>

            <div class="flow-end">
              <div class="flow-connector"></div>
              <div class="end-node">
                <i class="el-icon-s-release"></i>
                <span>结束</span>
              </div>
            </div>
          </template>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="orderDetailVisible" width="700px" append-to-body>
      <div v-loading="orderDetailLoading" class="order-detail-container">
        <div v-if="orderDetail" class="order-detail">
          <el-descriptions title="基本信息" :column="2" border>
            <el-descriptions-item label="订单ID">{{ orderDetail.orderId }}</el-descriptions-item>
            <el-descriptions-item label="订单号">{{ orderDetail.orderNumber }}</el-descriptions-item>
            <el-descriptions-item label="供应商ID">{{ orderDetail.supplierId }}</el-descriptions-item>
            <el-descriptions-item label="客户ID">{{ orderDetail.customerId }}</el-descriptions-item>
            <el-descriptions-item label="订单金额">¥{{ orderDetail.orderAmount }}</el-descriptions-item>
            <el-descriptions-item label="支付方式">{{ orderDetail.paymentMethod }}</el-descriptions-item>
            <el-descriptions-item label="订单日期">{{ orderDetail.orderDate }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="orderDetail.orderStatus === '0' ? 'success' : 'warning'">
                {{ orderDetail.orderStatus === '0' ? '已支付' : '待支付' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="地址ID" v-if="orderDetail.addressId">
              {{ orderDetail.addressId }}
            </el-descriptions-item>
          </el-descriptions>

          <div class="order-remark" v-if="orderDetail.remark">
            <div class="section-title">备注信息</div>
            <div class="remark-content">{{ orderDetail.remark }}</div>
          </div>
        </div>
        <div v-else class="no-data">
          <i class="el-icon-warning-outline"></i>
          <p>未找到订单数据</p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="orderDetailVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 二维码预览对话框 -->
    <el-dialog title="审批节点电子签名二维码" :visible.sync="qrCodeVisible" width="400px" append-to-body>
      <div class="qrcode-container">
        <div class="qrcode-tips">
          <p>审批节点: {{ currentNodeName }}</p>
          <p>订单ID: {{ currentNodeOrderId }}</p>
          <p>节点唯一标识: {{ getNodeUniqueId() }}</p>
        </div>
        <div class="qrcode-image">
          <el-image
            :src="qrCodeUrl"
            fit="contain"
            style="width: 200px; height: 200px;">
            <div slot="error" class="qrcode-sample">
              <i class="el-icon-mobile-phone" style="font-size: 50px;"></i>
              <p>二维码生成示意</p>
            </div>
          </el-image>
        </div>
        <div class="qrcode-desc">
          <p>扫描二维码进入电子签名页面</p>
          <p>签名页面将记录签名人和签名时间</p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qrCodeVisible = false">关 闭</el-button>
        <el-button type="primary" @click="downloadQrCode">下载二维码</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入API接口
import {
  listTemplate,
  getTemplate,
  addTemplate,
  updateTemplate,
  delTemplate
} from "@/api/supply/template";
import {getToken} from "@/utils/auth";
// 导入拖拽组件
import draggable from 'vuedraggable';
// 导入订单相关API
import {listPsorders, getPsorders} from "@/api/supply/psorders";
import {getProdinfo} from "@/api/supply/prodinfo";
// 添加QRCode生成库
import QRCode from 'qrcode';
//用户存储
import store from "@/store";

export default {
  name: "LeaderApproval",
  dicts: ['sys_normal_disable'],
  components: {
    draggable
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审批流程模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示预览弹出层
      previewOpen: false,
      // 预览数据
      previewData: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: undefined,
        flowType: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        templateName: undefined,
        templateDesc: undefined,
        flowType: 'purchase',
        processNodes: undefined,
        status: "0",
        orderId: undefined
      },
      // 表单校验
      rules: {
        templateName: [
          {required: true, message: "模板名称不能为空", trigger: "blur"},
          {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
        ],
        flowType: [
          {required: true, message: "流程类型不能为空", trigger: "change"}
        ]
      },
      // 节点列表
      nodeList: [],
      // 节点对话框可见性
      nodeDialog: false,
      // 节点表单
      nodeForm: {
        isNew: true,
        nodeName: '',
        approvalRoles: [],
        approvalRolesInput: '',
        approvalUsers: [],
        approvalUsersInput: '',
        approverCount: 1,
        needSignature: false,
        nodeId: ''
      },
      // 节点表单规则
      nodeRules: {
        nodeName: [
          {required: true, message: "节点名称不能为空", trigger: "blur"}
        ],
        approvalRolesInput: [
          {required: true, message: "至少输入一个审批角色", trigger: "blur"}
        ],
        approvalUsersInput: [
          {required: true, message: "至少输入一个审批人员姓名", trigger: "blur"}
        ]
      },
      // 审批人列表
      userList: [],
      // 当前编辑节点索引
      editIndex: -1,
      // 激活的标签页
      activeName: 'basic',
      // 二维码对话框
      qrCodeVisible: false,
      currentNodeName: '',
      currentNodeOrderId: '',
      currentNodeId: '',
      qrCodeUrl: '',
      baseUrl: '',
      // 订单选择对话框
      orderSelectDialogVisible: false,
      // 订单查询参数
      orderQueryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: undefined,
        orderDate: undefined,
        orderStatus: undefined,
        customerId: this.$store.getters.userId
      },
      // 订单列表数据
      orderList: [],
      // 订单总条数
      orderTotal: 0,
      // 订单加载状态
      orderLoading: false,
      // 订单详情对话框
      orderDetailVisible: false,
      // 订单详情数据
      orderDetail: null,
      // 订单详情加载状态
      orderDetailLoading: false,
      // 为模板选择订单标记
      isSelectingForTemplate: false,
      // 当前编辑节点
      currentNode: null
    };
  },
  created() {
    this.getList();
    this.baseUrl = window.location.origin || "http://10.18.38.35";
  },
  methods: {
    /** 查询审批流程模板列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;

        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error("获取模板列表失败:", error);
        this.loading = false;
      });
    },
    /** 获取审批人员列表 */
    getUserList() {
      // 这个方法不再需要获取用户列表数据，因为用户将直接输入名称
      // 可以保留空方法或者完全移除
    },
    // 审批流程类型翻译
    flowTypeFormat(row, column) {
      const flowTypes = {
        'purchase': '采购审批',
        'sales': '销售审批',
        'hr': '人事审批',
        'finance': '财务审批',
        'other': '其他审批'
      };
      return flowTypes[row.flowType] || row.flowType;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        templateName: undefined,
        templateDesc: undefined,
        flowType: 'purchase',
        processNodes: undefined,
        status: "0",
        orderId: undefined
      };
      this.nodeList = [];
      this.activeName = 'basic';
      this.resetForm("form");
      this.isSelectingForTemplate = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加审批流程模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row?.id || this.ids[0];
      getTemplate(id).then(response => {
        if (response.data) {
          this.form = response.data;

          // 修改这里，从processNodes读取节点数据而不是formJson
          if (this.form.processNodes) {
            try {
              const formData = JSON.parse(this.form.processNodes);
              this.nodeList = formData.nodes || [];
            } catch (e) {
              console.error('解析流程配置出错', e);
            }
          }
          this.open = true;
          this.title = "修改审批流程模板";
        }
      }).catch(error => {
        console.error("获取模板详情失败:", error);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 获取流程设计数据
          let flowData = {
            nodes: this.nodeList,
            version: "1.0"
          };

          this.form.processNodes = JSON.stringify(flowData);

          if (this.form.id) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("更新模板失败:", error);
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("新增模板失败:", error);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row?.id || this.ids;
      this.$modal.confirm('是否确认删除审批流程模板编号为"' + ids + '"的数据项？').then(() => {
        delTemplate(ids).then(response => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        }).catch(error => {
          console.error("删除模板失败:", error);
        });
      }).catch(() => {
      });
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      console.log("row:", row)
      if (!row.processNodes) {
        this.$modal.msgError("该模板没有流程设计内容，无法预览");
        return;
      }

      try {
        const formData = JSON.parse(row.processNodes);

        // 确保节点有nodeId
        if (formData.nodes && formData.nodes.length) {
          formData.nodes.forEach(node => {
            if (!node.nodeId) {
              node.nodeId = this.generateNodeId();
            }
          });
        }

        this.previewData = formData;
        this.previewData.orderId = row.orderId;
        console.log("this.previewData:", this.previewData)
        this.previewOpen = true;
      } catch (e) {
        this.$modal.msgError("流程设计数据解析错误，无法预览");
        console.error("预览流程数据解析错误", e);
      }
    },

    // ===== 流程设计拖拽相关方法 =====
    // 处理节点拖动开始
    handleDragStart(event, nodeType) {
      event.dataTransfer.setData('nodeType', nodeType);
    },

    // 处理节点放置
    handleDrop(event) {
      const nodeType = event.dataTransfer.getData('nodeType');
      if (nodeType) {
        this.addNode(nodeType);
      }
    },

    // 手动添加节点
    addNodeManually() {
      this.nodeForm = {
        isNew: true,
        nodeName: '',
        approvalRoles: [],
        approvalRolesInput: '',
        approvalUsers: [],
        approvalUsersInput: '',
        approverCount: 1,
        needSignature: false,
        nodeId: this.generateNodeId()
      };
      this.editIndex = -1;
      this.nodeDialog = true;
    },

    // 添加节点
    addNode(nodeType) {
      this.editIndex = -1;
      this.nodeForm = {
        isNew: true,
        nodeName: '审批节点',
        approvalRolesInput: '',
        approvalUsersInput: '',
        approverCount: 1,
        needSignature: false,
        nodeId: this.generateNodeId()
      };
      this.nodeDialog = true;
    },

    /** 编辑节点 */
    editNode(node, index) {
      this.nodeForm = {
        isNew: false,
        nodeName: node.nodeName,
        approvalRoles: node.approvalRoles || [],
        approvalRolesInput: node.approvalRoles ? node.approvalRoles.join(', ') : '',
        approvalUsers: node.approvalUsers || [],
        approvalUsersInput: node.approvalUsers ? node.approvalUsers.join(', ') : '',
        approverCount: node.approverCount || 1,
        needSignature: node.needSignature || false,
        nodeId: node.nodeId || this.generateNodeId()
      };
      this.editIndex = index;
      this.nodeDialog = true;
    },

    /** 删除节点 */
    deleteNode(index) {
      this.$modal.confirm('确认要删除该审批节点吗？').then(() => {
        this.nodeList.splice(index, 1);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 提交节点表单 */
    submitNodeForm() {
      this.$refs.nodeForm.validate(valid => {
        if (valid) {
          try {
            // 确保转换输入文本为数组
            this.handleRolesInput();
            this.handleUsersInput();

            const node = {
              nodeName: this.nodeForm.nodeName,
              approvalRoles: this.nodeForm.approvalRoles || [],
              approvalUsers: this.nodeForm.approvalUsers || [],
              approverCount: this.nodeForm.approverCount || 1,
              needSignature: this.nodeForm.needSignature,
              nodeId: this.nodeForm.nodeId || this.generateNodeId()
            };

            if (this.editIndex > -1) {
              // 编辑模式
              this.nodeList.splice(this.editIndex, 1, node);
            } else {
              // 新增模式
              this.nodeList.push(node);
            }

            this.nodeDialog = false;
            this.$modal.msgSuccess("保存节点成功");
          } catch (error) {
            console.error("节点保存错误:", error);
            this.$modal.msgError("节点保存失败");
          }
        }
      });
    },

    /** 预览电子签名二维码 */
    previewQrCode(node) {
      console.log("node:", node);
      this.currentNodeName = node.nodeName;
      this.currentNode = node; // 保存当前节点信息

      // 确保获取正确的orderId，先从form中获取，再从previewData中获取
      this.currentNodeOrderId = this.form.orderId || (this.previewData && this.previewData.orderId) || '';
      this.currentNodeId = node.nodeId;

      if (!this.currentNodeOrderId) {
        this.$message.warning('请先关联订单后再生成二维码');
        return; // 如果没有orderId，直接返回，不继续执行
      }

      // 生成二维码链接
      this.generateQrCode();
      this.qrCodeVisible = true;
    },

    /** 生成节点唯一ID */
    generateNodeId() {
      return 'node_' + new Date().getTime() + '_' + Math.floor(Math.random() * 1000);
    },

    /** 获取节点唯一标识符（用于二维码内容） */
    getNodeUniqueId() {
      return `${this.currentNodeOrderId}_${this.currentNodeId}`;
    },

    /** 生成二维码 */
    generateQrCode() {
      // 再次验证必要参数
      if (!this.currentNodeOrderId || !this.currentNodeId) {
        this.$message.warning('缺少生成二维码的必要参数');
        return;
      }

      // 构建二维码内容URL（审批页面地址）
      const approvalRoles = this.formatRoles(this.currentNode?.approvalRoles || []);
      const approvalUsers = this.formatApprovalUsers(this.currentNode?.approvalUsers || []);

      // 使用动态获取的baseUrl，而不是硬编码值
      const baseUrl = window.location.origin || this.baseUrl;

      const approvalUrl = `${baseUrl}/supply/signature?orderId=${this.currentNodeOrderId}&nodeId=${this.currentNodeId}&nodeName=${encodeURIComponent(this.currentNodeName)}&approvalRoles=${encodeURIComponent(approvalRoles)}&approvalUsers=${encodeURIComponent(approvalUsers)}&token=${encodeURIComponent(store.getters.token)}`;

      console.log("生成二维码URL:", approvalUrl); // 添加日志便于调试

      // 使用qrcode库生成二维码
      QRCode.toDataURL(approvalUrl)
        .then(url => {
          this.qrCodeUrl = url;
        })
        .catch(err => {
          console.error('二维码生成失败:', err);
          this.$message.error('二维码生成失败');
          this.qrCodeUrl = '';
        });
    },

    /** 下载二维码 */
    downloadQrCode() {
      if (!this.qrCodeUrl) {
        this.$message.warning('二维码尚未生成');
        return;
      }

      // 创建下载链接
      const link = document.createElement('a');
      link.download = `approval_qrcode_${this.currentNodeOrderId}_${this.currentNodeName}.png`;
      link.href = this.qrCodeUrl;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // ===== 订单选择相关方法 =====
    // 打开订单选择对话框 - 针对模板
    openOrderSelectForTemplate() {
      this.isSelectingForTemplate = true;
      this.openOrderSelectDialog();
    },

    // 打开订单选择对话框
    openOrderSelectDialog() {
      this.orderSelectDialogVisible = true;
      this.resetOrderSearch();
      this.getOrderList();
    },

    // 搜索订单
    searchOrders() {
      this.orderQueryParams.pageNum = 1;
      this.getOrderList();
    },

    // 重置订单搜索条件
    resetOrderSearch() {
      this.orderQueryParams = {
        pageNum: 1,
        pageSize: 10,
        orderNumber: undefined,
        orderDate: undefined,
        orderStatus: undefined,
        customerId: this.$store.getters.userId

      };
      this.getOrderList();
    },

    // 获取订单列表
    getOrderList() {
      this.orderLoading = true;

      listPsorders(this.orderQueryParams).then(response => {
        console.log("this.orderQueryParams",this.orderQueryParams)
        this.orderList = response.rows;
        this.orderTotal = response.total;
        this.orderLoading = false;
      }).catch(() => {
        // 如果API调用失败，使用模拟数据
        setTimeout(() => {
          this.orderList = this.mockData.orderList;
          this.orderTotal = this.mockData.orderList.length;
          this.orderLoading = false;
        }, 500);
      });
    },

    // 点击行选择订单
    handleOrderSelect(row) {
      this.selectOrder(row);
    },

    // 选择订单
    selectOrder(row) {
      if (this.isSelectingForTemplate) {
        // 为模板选择订单
        this.form.orderId = row.orderId;
        this.isSelectingForTemplate = false;
      } else {
        // 这部分代码可以保留，以备将来需要在某些特殊情况下为节点选择订单
        this.nodeForm.orderId = row.orderId;
      }
      this.orderSelectDialogVisible = false;
      this.$message.success(`已选择订单ID：${row.orderId}`);
    },

    // 处理角色输入
    handleRolesInput() {
      if (this.nodeForm.approvalRolesInput) {
        this.nodeForm.approvalRoles = this.nodeForm.approvalRolesInput.split(',').map(item => item.trim());
      } else {
        this.nodeForm.approvalRoles = [];
      }
    },

    // 处理用户输入
    handleUsersInput() {
      if (this.nodeForm.approvalUsersInput) {
        this.nodeForm.approvalUsers = this.nodeForm.approvalUsersInput.split(',').map(item => item.trim());
      } else {
        this.nodeForm.approvalUsers = [];
      }
    },

    // 格式化多个审批角色
    formatRoles(roleKeys) {
      if (!roleKeys || !roleKeys.length) return '无';
      return roleKeys.join(', ');
    },

    // 格式化审批人员
    formatApprovalUsers(userIds) {
      if (!userIds || !userIds.length) return '无';
      return userIds.join(', ');
    },

    /** 查看订单详情 */
    viewOrderDetails(orderId) {
      if (!orderId) {
        this.$message.warning('未关联订单');
        return;
      }

      this.orderDetailLoading = true;
      this.orderDetailVisible = true;
      this.orderDetail = null;

      // 通过API获取订单详情
      getPsorders(orderId).then(response => {
        if (response && response.data) {
          // 直接使用后端返回的数据
          this.orderDetail = response.data;
          this.orderDetailLoading = false;
        } else {
          this.$message.warning('未找到订单数据');
          this.orderDetailLoading = false;
        }
      }).catch(err => {
        console.error('获取订单详情失败:', err);
        this.$message.error('获取订单详情失败');
        this.orderDetailLoading = false;
      });
    },

    /** 获取单个商品详情 */
    fetchProductDetail(productId, quantity) {
      if (!productId) return;

      getProdinfo(productId).then(response => {
        if (response && response.data) {
          // 更新商品信息
          this.orderDetail.products = [{
            productId: productId,
            name: response.data.name || '未知商品',
            unitPrice: response.data.unitPrice || 0,
            quantity: quantity || 1
          }];
        }
      }).catch(() => {
        // 如果获取商品信息失败，使用默认值
        this.orderDetail.products = [{
          productId: productId,
          name: '商品信息获取失败',
          unitPrice: this.orderDetail.orderAmount / quantity || 0,
          quantity: quantity || 1
        }];
      });
    },

    // 获取签名图片
    getSignatureImages(signatureImage) {
      if (!signatureImage) return [];
      // 分割逗号分隔的图片链接
      return signatureImage.split(',').filter(img => img.trim() !== '');
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.expr-tips {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 5px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

/* 流程设计相关样式 */
.flow-design-container {
  display: flex;
  height: 600px;
  border: 1px solid #ebeef5;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
}

.node-toolbox {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid #ebeef5;
  padding: 15px;

  .toolbox-title {
    font-weight: bold;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 15px;
  }

  .node-item-list {
    .node-item {
      display: flex;
      align-items: center;
      padding: 10px;
      background-color: #ecf5ff;
      border: 1px dashed #409EFF;
      border-radius: 4px;
      margin-bottom: 10px;
      cursor: move;

      i {
        margin-right: 8px;
        font-size: 16px;
      }

      &:hover {
        background-color: #d9ecff;
        border-style: solid;
      }
    }
  }
}

.flow-canvas {
  flex: 1;
  padding: 20px;
  overflow: auto;
  background-color: #fff;
  position: relative;

  .flow-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #909399;

    i {
      font-size: 32px;
      margin-bottom: 10px;
    }

    p {
      margin-bottom: 15px;
    }
  }

  .flow-start, .flow-end {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;

    .start-node, .end-node {
      width: 100px;
      height: 40px;
      border-radius: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;

      i {
        margin-right: 5px;
      }
    }

    .start-node {
      background-color: #e1f3d8;
      color: #67c23a;
      border: 1px solid #67c23a;
    }

    .end-node {
      background-color: #fef0f0;
      color: #f56c6c;
      border: 1px solid #f56c6c;
    }

    .flow-connector {
      height: 30px;
      width: 2px;
      background-color: #dcdfe6;
      margin: 5px 0;
    }
  }

  .node-list {
    width: 100%;
  }

  .flow-node-wrapper {
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;

    .flow-node {
      width: 300px;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;

      &.approval-node {
        border-left: 3px solid #409EFF;
        background-color: #ecf5ff;
      }

      .node-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        padding-bottom: 10px;
        border-bottom: 1px solid #ebeef5;

        .node-title {
          font-weight: bold;
          display: flex;
          align-items: center;

          i {
            margin-right: 5px;
          }
        }

        .node-actions {
          display: flex;
          gap: 8px;

          i {
            cursor: pointer;
            font-size: 16px;

            &.el-icon-delete:hover {
              color: #F56C6C;
            }

            &.el-icon-edit:hover {
              color: #409EFF;
            }

            &.node-drag-handle {
              cursor: move;

              &:hover {
                color: #909399;
              }
            }
          }
        }
      }

      .node-content {
        .node-info {
          font-size: 13px;
          color: #606266;

          .info-item {
            margin: 5px 0;
            display: flex;

            .info-label {
              width: 80px;
              color: #909399;
            }

            .info-value {
              flex: 1;
            }
          }
        }
      }
    }

    .flow-connector {
      height: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;

      &:before {
        content: '';
        position: absolute;
        top: 0;
        bottom: 0;
        left: 50%;
        width: 2px;
        background-color: #dcdfe6;
        transform: translateX(-50%);
      }

      i {
        position: relative;
        z-index: 1;
        background-color: #fff;
        color: #dcdfe6;
      }
    }
  }
}

.ghost-node {
  opacity: 0.5;
  background: #c8ebfb;
  border: 1px dashed #409EFF !important;
}

/* 流程预览样式 */
.flow-preview-container {
  width: 100%;
  height: 500px;
  overflow: auto;
  border: 1px solid #ebeef5;
  background-color: #fafafa;
  padding: 20px;
}

.flow-preview {
  .no-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #909399;

    i {
      font-size: 32px;
      margin-bottom: 10px;
    }
  }

  .flow-info {
    margin-top: 30px;
    padding: 15px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;

    h3 {
      margin-top: 0;
      margin-bottom: 10px;
      font-size: 16px;
      color: #606266;
    }

    p {
      margin: 5px 0;
      color: #67c23a;
    }
  }
}

/* 电子签名样式 */
.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;

  .qrcode-tips {
    text-align: center;
    margin-bottom: 20px;

    p {
      margin: 5px 0;
      font-size: 14px;
      color: #606266;

      &:first-child {
        font-weight: bold;
        font-size: 16px;
        margin-bottom: 15px;
      }
    }
  }

  .qrcode-image {
    margin-bottom: 20px;
  }

  .qrcode-desc {
    text-align: center;
  }
}

/* 订单选择对话框样式 */
.order-select-dialog {
  .order-search-form {
    margin-bottom: 15px;
  }

  .selected-order {
    margin-top: 10px;
    padding: 10px;
    border: 1px solid #e1f3d8;
    background-color: #f0f9eb;
    border-radius: 4px;
    position: relative;

    p {
      margin: 5px 0;
      font-size: 14px;

      span {
        font-weight: bold;
        margin-right: 5px;
      }
    }

    .el-button {
      position: absolute;
      right: 5px;
      top: 5px;
    }
  }
}

.el-tabs {
  .el-tabs__header {
    margin-bottom: 20px !important;
  }
}

.el-form-item {
  margin-bottom: 22px;
}

.qrcode-btn {
  margin-left: 5px;
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;

  .qrcode-tips {
    text-align: center;
    margin-bottom: 20px;

    p {
      margin: 5px 0;
      font-size: 14px;
      color: #606266;

      &:first-child {
        font-weight: bold;
        font-size: 16px;
        margin-bottom: 15px;
      }
    }
  }

  .qrcode-image {
    margin: 20px 0;
    border: 1px solid #ebeef5;
    padding: 10px;
    border-radius: 4px;
  }

  .qrcode-desc {
    margin-top: 15px;
    text-align: center;

    p {
      margin: 5px 0;
      font-size: 14px;
      color: #909399;
    }
  }

  .qrcode-sample {
    width: 200px;
    height: 200px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    color: #606266;

    p {
      margin-top: 10px;
      font-size: 12px;
    }
  }
}

/* 订单详情对话框样式 */
.order-detail-container {
  min-height: 300px;

  .section-title {
    font-weight: bold;
    margin: 20px 0 10px;
    border-left: 3px solid #409EFF;
    padding-left: 10px;
  }

  .order-goods {
    margin-top: 20px;
  }

  .order-address {
    margin-top: 20px;

    .address-content {
      padding: 10px;
      background-color: #f8f8f8;
      border-radius: 4px;
    }
  }

  .no-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #909399;

    i {
      font-size: 32px;
      margin-bottom: 10px;
    }
  }
}

.btn-margin {
  margin-left: 10px;
}

.success-icon {
  color: #67c23a;
}

.order-remark {
  margin-top: 20px;

  .remark-content {
    padding: 10px;
    background-color: #f8f8f8;
    border-radius: 4px;
    white-space: pre-wrap;
    word-break: break-all;
  }
}

.signature-images {
  margin-top: 10px;

  p {
    margin-bottom: 8px;
    font-weight: bold;
    color: #606266;
  }

  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .signature-thumb {
      width: 80px;
      height: 80px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 2px;
      cursor: pointer;

      &:hover {
        border-color: #409EFF;
      }
    }

    .image-error {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      background: #f5f7fa;
      color: #909399;
      font-size: 14px;
    }
  }
}

.signature-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;

  .signature-thumb {
    width: 40px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 2px;
    cursor: pointer;

    &:hover {
      border-color: #409EFF;
    }
  }

  .image-error {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 14px;
  }
}
</style>
